/**
 * Copyright 2009 University of Washington This code is released under the GPL version 3 - with a copy of the license
 * included
 * 
 * @author Maya Hao Li
 */
package seedpod.webapp.controller;

/**
 * Process a create instance form submission
 */

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import seedpod.exceptions.DataValidationException;
import seedpod.exceptions.SeedpodException;
import seedpod.kb2db.ClsMap;
import seedpod.kb2db.SlotMap;
import seedpod.model.AVPair;
import seedpod.model.SeedpodDO;
import seedpod.rdb.PMFactory;
import seedpod.rdb.PManager;
import seedpod.util.Util;
import seedpod.webapp.LimsSession;
import seedpod.webapp.Seedpod;
import seedpod.webapp.view.InstanceRenderer;
import seedpod.webapp.view.seedpodwidgets.LimsWidget;
import seedpod.webapp.view.seedpodwidgets.LimsWidgetFactory;

public class ActionNewInstance extends HttpServlet {

	private static final long serialVersionUID = -1382509010699123214L;
	public static final String URL = "newInstance";
	private String _clsName;
	private int _oid;
	private SeedpodDO _object;
	private PManager _manager;

	@Override
	public void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException {
	// DO NOTHING
	}

	@Override
	public void doPost( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		String displayUrl;
		String pageMsg = "";
		LimsSession spSession = LimsSession.getSession( request );
		ClsMap clsMap = null;
		boolean hasError = false;

		if ( _manager == null ) {
			out.println( "Cannot connect to the database. " );
			return;
		}

		initRequiredField( request );

		clsMap = _manager.getModelMap().getClsMap( _clsName );

		if ( clsMap == null ) {
			pageMsg = "I can't create an instance of " + _clsName;
			spSession.setAttribute( InstanceRenderer.PAGE_MSG, pageMsg );
			out.println( pageMsg );
			return;
		}

		_object = _manager.createObject( _clsName );
		_object.markDirty();

		HashMap<String, DataValidationException> validationErr = new HashMap<String, DataValidationException>();

		ArrayList<SlotMap> slots = new ArrayList<SlotMap>( _object.getMetaSlots() );
		for ( SlotMap slot : slots ) {
			AVPair avBinder = _object.getAVPair( slot );
			Object submittedValue = request.getParameter( avBinder.genRefId() );
			avBinder.setValue( submittedValue );

			System.err.println( "submitted val for " + avBinder.genRefId() + " = " + submittedValue );

			LimsWidget formWidget = LimsWidgetFactory.getEditWidget( avBinder );
			try {
				formWidget.validateSubmissionData( submittedValue );
			} catch (DataValidationException e) {
				validationErr.put( avBinder.genRefId(), e );
			}
		}
		displayUrl = "../lims/instance.jsp?" + InstanceRenderer.CLSNAME + "=" + _clsName;
		displayUrl += "&" + InstanceRenderer.OID + "=" + _oid;

		spSession.setAttribute( Util.getSeedpodInternalId( _object ), _object );

		if ( validationErr.size() > 0 ) hasError = true;

		if ( !hasError ) try {
			_object.create();
			_oid = _object.getOid();
			pageMsg = "New object saved.";
			spSession.setAttribute( InstanceRenderer.PAGE_MSG, pageMsg );

			Logger.write( spSession.getUser(), "Create new object " + _oid );

			displayUrl += "&" + InstanceRenderer.ACTION + "=" + InstanceRenderer.ACTION_VIEW;
			Util.redirect( displayUrl, request, response );
		} catch (SeedpodException e) {
			// spSession.addSessionErrorMsg( e.getMessage() );
			// Util.redirect( "error.jsp", request, response );
			pageMsg += e.getMessage();
			spSession.setAttribute( InstanceRenderer.PAGE_MSG, pageMsg );
			hasError = true;
		}

		if ( hasError ) {
			_object.markDirty();
			pageMsg += "<br>Please correct the following error(s).";
			spSession.setAttribute( InstanceRenderer.VALIDATION_ERROR, validationErr );
			spSession.setAttribute( InstanceRenderer.PAGE_MSG, pageMsg );

			displayUrl += "&" + InstanceRenderer.ACTION + "=" + InstanceRenderer.ACTION_EDIT;
			Util.redirect( displayUrl, request, response );
		}
	}

	@Override
	public void init() {
		try {
			PMFactory factory = Seedpod.getPersistenceManagerFactory();
			_manager = factory.createManager();
		} catch (SeedpodException se) {
			System.err.println( " Cannot find valid Persistence Manager. " + se.getMessage() );
		}
	}

	/** required variables * */
	private void initRequiredField( HttpServletRequest request ) {
		_clsName = request.getParameter( InstanceRenderer.CLSNAME );
	}

}
